﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GTA
{
    public partial class FrmGroups : BaseForm
    {
        #region Local Objects
        private BusinessEntity.Group groupEdit;
        private List<BusinessEntity.Group> listGroups;
        #endregion

        #region Starting Form
        public FrmGroups()
        {
            InitializeComponent();
        }
        private void FrmGroups_Load(object sender, EventArgs e)
        {
            StartForm();
        }
        private void StartForm()
        {
            try
            {
                LoadCurrentGroups();
            }
            catch (Exception ex)
            {
                HandleException("Inicialização da tela.", ex);
            }
        }
        #endregion

        #region Events
        private void cmdSave_Click(object sender, EventArgs e)
        {
            SaveGroup();
        }
        private void cmdClean_Click(object sender, EventArgs e)
        {
            CleanForm();
        }
        private void cmdEdit_Click(object sender, EventArgs e)
        {
            EditSelectedGroup();
        }
        private void cmdDelete_Click(object sender, EventArgs e)
        {
            DeleteSelectedGroups();
        }
        private void editarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditSelectedGroup();
        }
        private void excluirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteSelectedGroups();
        }
        private void lstGroups_DoubleClick(object sender, EventArgs e)
        {
            EditSelectedGroup();
        }
        private void lstGroups_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            SortList(lstGroups, GetColumnType(e.Column), ref columnOrder, ref sortOrder, e.Column);
        }
        private void lstGroups_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                DeleteSelectedGroups();
        }
        private void lstGroups_Resize(object sender, EventArgs e)
        {
            lstGroups.Columns[3].Width = lstGroups.Width - lstGroups.Columns[0].Width - lstGroups.Columns[1].Width - lstGroups.Columns[2].Width - 23;
        }
        #endregion

        #region Methods
        private void LoadCurrentGroups()
        {
            try
            {
                BusinessLogic.GTA bl = new BusinessLogic.GTA();
                listGroups = bl.ListGroups();
                lstGroups.Items.Clear();
                if (listGroups != null && listGroups.Count > 0)
                {
                    foreach (BusinessEntity.Group itemGroup in listGroups)
                    {
                        ListViewItem listItem = new ListViewItem(itemGroup.ID.ToString());
                        listItem.SubItems.Add(itemGroup.Name);
                        listItem.SubItems.Add(itemGroup.Identification);
                        listItem.SubItems.Add(itemGroup.Description);
                        lstGroups.Items.Add(listItem);
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Carregar os grupos atuais", ex);
            }
        }
        private void SaveGroup()
        {
            try
            {
                if (ValidateForm())
                {
                    BusinessEntity.Group group = GetGroupData();
                    BusinessLogic.GTA bl = new BusinessLogic.GTA();
                    bl.SaveGroup(group);
                    MessageBox.Show("Grupo salvo com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    CleanForm();
                    LoadCurrentGroups();
                }
            }
            catch (Exception ex)
            {
                HandleException("Salvar um novo grupo", ex);
            }
        }
        private bool ValidateForm()
        {
            bool valid = true;
            StringBuilder message = new StringBuilder("Informe os campos obrigatórios:\r\n");

            if (String.IsNullOrEmpty(txtIdentification.Text.Trim()))
            {
                valid = false;
                message.Append("Identificação do Grupo");
            }
            if (String.IsNullOrEmpty(txtName.Text.Trim()))
            {
                valid = false;
                message.Append("Nome do Grupo");
            }

            if (!valid)
                MessageBox.Show(message.ToString(), "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return valid;
        }
        private BusinessEntity.Group GetGroupData()
        {
            BusinessEntity.Group group = new GTA.BusinessEntity.Group();
            if (groupEdit != null)
                group.ID = groupEdit.ID;
            group.Name = txtName.Text.Trim();
            group.Identification = txtIdentification.Text.Trim();
            group.Description = txtDescription.Text.Trim();
            return group;
        }
        private void CleanForm()
        {
            txtName.Text = String.Empty;
            txtIdentification.Text = String.Empty;
            txtDescription.Text = String.Empty;
            groupEdit = null;
            txtName.Focus();
        }
        private void EditSelectedGroup()
        {
            try
            {
                if (lstGroups.SelectedItems.Count == 1 && listGroups != null)
                {
                    groupEdit = listGroups.Find(it => it.ID.CompareTo(Convert.ToInt32(lstGroups.SelectedItems[0].SubItems[0].Text)) == 0);
                    if (groupEdit != null)
                    {
                        txtName.Text = groupEdit.Name;
                        txtIdentification.Text = groupEdit.Identification;
                        txtDescription.Text = groupEdit.Description;
                        txtName.Focus();
                    }
                }
                else
                    MessageBox.Show("Selecione somente um grupo para editar!", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                HandleException("Editar um grupo", ex);
            }
        }
        private void DeleteSelectedGroups()
        {
            try
            {
                if (lstGroups.SelectedItems.Count > 0)
                {
                    if (MessageBox.Show("Deseja realmente excluir os grupos selecionados?", "Questão", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        BusinessLogic.GTA bl = new BusinessLogic.GTA();
                        while (lstGroups.SelectedItems.Count > 0)
                        {
                            BusinessEntity.Group itemGroup = listGroups.Find(it => it.ID.CompareTo(Convert.ToInt32(lstGroups.SelectedItems[0].SubItems[0].Text)) == 0);
                            bl.DeleteGroup(itemGroup.ID);
                            lstGroups.SelectedItems[0].Remove();
                        }
                        MessageBox.Show("Grupos excluídos com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadCurrentGroups();
                    }
                }
                else
                    MessageBox.Show("Selecione ao menos um grupo para excluir!", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                HandleException("Excluir os grupos selecionados", ex);
            }
        }
        private OrdenacaoListView.Tipo GetColumnType(Int32 column)
        {
            OrdenacaoListView.Tipo columnType;
            switch (column)
            {
                case 0:
                    columnType = OrdenacaoListView.Tipo.Numerica;
                    break;
                case 1:
                    columnType = OrdenacaoListView.Tipo.Alfabetica;
                    break;
                case 2:
                    columnType = OrdenacaoListView.Tipo.Alfabetica;
                    break;
                default:
                    columnType = OrdenacaoListView.Tipo.Alfabetica;
                    break;
            }
            return columnType;
        }
        #endregion
    }
}
